import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_wear_app/global/index.dart';
import 'package:flutter_wear_app/setting.dart';
import 'package:flutter_wear_app/utils/http_util.dart';
import 'package:hive_flutter/adapters.dart';
import 'package:wear_plus/wear_plus.dart';



Future<void> main() async {
  // 初始化 Hive
  await Hive.initFlutter();
  // 打开盒子
  await Hive.openBox('myBox');

  HttpUtil.initialize();
  // 确保 Flutter 框架初始化完成
  WidgetsFlutterBinding.ensureInitialized();


  await initializeService();
  // 运行应用程序
  runApp(const MyApp());
}

Future<void> initializeService() async {
  final service = FlutterBackgroundService();
  await service.configure(
    androidConfiguration: AndroidConfiguration(
      onStart: onStart,
      autoStart: true,
      isForegroundMode: true,
    ),
    iosConfiguration: IosConfiguration(
      autoStart: true,
      onForeground: onStart,
      onBackground: onIosBackground,
    ),
  );
  await service.startService();
}

@pragma('vm:entry-point')
void onStart(ServiceInstance service) async {
  if (service is AndroidServiceInstance) {
    service.setForegroundNotificationInfo(
      title: "安全监护服务",
      content: "最后活跃: ${DateTime.now().toString().substring(11, 16)}",
    );
  }

  // 这里可以执行后台任务
  initBusState();

  Timer.periodic(Duration(seconds: 10), (timer) async {
    if (service is AndroidServiceInstance) {
      // 更新前台服务通知
      print("前台服务正在运行");
      service.setForegroundNotificationInfo(
        title: "后台服务运行中",
        content: "最后活跃: ${DateTime.now()}",
      );
    }
  });
}

@pragma('vm:entry-point')
Future<bool> onIosBackground(ServiceInstance service) async {
  // 处理 iOS 后台任务
  return true;
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    init();
  }

  @override
  void dispose() {
    super.dispose();
    disposeAll();
  }

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: const Size(360, 360),
      minTextAdapt: true,
      builder: (context, child) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          theme: ThemeData(
            primarySwatch: Colors.blue,
            platform: TargetPlatform.iOS,
          ),
          home: Scaffold(
            body: Center(
              child: PageView(
                scrollDirection: Axis.vertical,
                children: [
                  GroupItem(
                    showChild: TextButton(
                      style: ButtonStyle(
                        // 设置按钮的固定大小
                        fixedSize: WidgetStateProperty.all(Size(.6.sw, .6.sh)),
                        // 设置按钮的对齐方式
                        alignment: Alignment.center,
                        // 设置按钮的背景颜色
                        backgroundColor: WidgetStateProperty.all(
                          const Color(0xFFF66600),
                        ),
                        // 设置按钮的边框圆角
                        shape: WidgetStateProperty.all(
                          RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20),
                          ),
                        ),
                      ),
                      onPressed: () {
                        sendSOS();
                      },
                      child: Text(
                        'SOS紧急呼救',
                        textAlign: TextAlign.center,
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 26,
                        ),
                      ),
                    ),
                  ),
                  GroupItem(
                    showChild: Builder(
                      builder: (BuildContext newContext) {
                        return TextButton(
                          onPressed: () {
                            Navigator.push(
                              newContext, // 使用新的 context
                              MaterialPageRoute(
                                builder: (context) {
                                  return Setting();
                                },
                              ),
                            );
                          },
                          style: ButtonStyle(
                            // 设置按钮的固定大小
                            fixedSize: WidgetStateProperty.all(
                              Size(.6.sw, .6.sh),
                            ),
                            // 设置按钮的对齐方式
                            alignment: Alignment.center,
                            // 设置按钮的背景颜色
                            backgroundColor: WidgetStateProperty.all(
                              const Color.fromARGB(255, 0, 86, 246),
                            ),
                            // 设置按钮的边框圆角
                            shape: WidgetStateProperty.all(
                              RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(20),
                              ),
                            ),
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              const Icon(
                                Icons.settings,
                                size: 40,
                                color: const Color.fromARGB(255, 255, 255, 255),
                              ),
                              Text(
                                '设置',
                                textAlign: TextAlign.center,
                                style: const TextStyle(
                                  color: Colors.white,
                                  fontSize: 26,
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}

class GroupItem extends StatelessWidget {
  final Widget showChild;
  const GroupItem({super.key, required this.showChild});

  @override
  Widget build(BuildContext context) {
    // 这里可以根据需求返回具体的 Widget
    return AmbientMode(
      builder: (context, mode, child) {
        return Container(
          alignment: Alignment.center,
          width: 360.w,
          height: 360.h,
          child: showChild,
        );
      },
    );
  }
}
